/*
 * @lc app=leetcode.cn id=56 lang=java
 *
 * [56] 合并区间
 */

// @lc code=start

import java.util.List;

class Solution {
    public int[][] merge(int[][] intervals) {
        List<int[]> res = new ArrayList<int[]>();

        if(intervals.length == 0) return res.toArray(new int[0][]);

        Arrays.sort(intervals, (x, y) -> x[0] - y[0]);

        int left = intervals[0][0], right = intervals[0][1];

        for(int i = 0; i < intervals.length; i++) {
            if(intervals[i][0] > right) {

                res.add(new int[]{left, right});
                left = intervals[i][0];
                right = intervals[i][1];

            } else {

                right = Math.max(right, intervals[i][1]);

            }
            
        }
        
        res.add(new int[]{left, right});
        return res.toArray(new int[res.size()][]);

    }
}
// @lc code=end

